//
//  OPMainVideoController.m
//  OnePiece
//
//  Created by wsy on 15/10/26.
//  Copyright © 2015年 wsy. All rights reserved.
//

#import "OPMainVideoController.h"
#import "OPEatListCell.h"
#import "OPRequesterManager.h"
#import "OPEatDetailController.h"
#import "OPEatListHeadView.h"
#import "OPEatMGuideController.h"
#import "OPEatRitListController.h"
#import "FMDatabase.h"
@interface OPMainVideoController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (nonatomic, strong) FMDatabase *dataBase;
@end

@implementation OPMainVideoController

- (NSMutableArray *)dataSourceArr{
    if (_dataSourceArr == nil) {
        _dataSourceArr = [NSMutableArray arrayWithCapacity:0];
    }
    return _dataSourceArr;
}
- (void)configureData
{
    NSString *urlstr = @"http://www.youyuwei.com/api/note?app_code=com.youyuwei.yuwei.ios&hardware_model=%2C2&app_ver=2.1&sys_ver=&device_type=ios&ywsdk_ver=20131018&open_udid=&start=0&oauth_timestamp=1445996518&list=Hotlist&device_token=&oauth_signature_method=HMAC-SHA1&x_auth_mode=client_auth&ver=2&idfa=&channel_id=App%20Store&oauth_version=1.0&oauth_consumer_key=4&oauth_token=&oauth_signature=%3D&debug=0&oauth_nonce=";

    [OPRequesterManager requestWithType:GET urlString:urlstr parDic:nil finish:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
        NSArray * array = dic[@"data"][@"list"];
        [self.dataSourceArr removeAllObjects];
        [_dataBase executeUpdate:@"delete from eat"];
        for (NSDictionary *dict in array) {
            OPEatListModel *m = [[OPEatListModel alloc]init];
            [m setValuesForKeysWithDictionary:dict];
            [self.dataSourceArr addObject:m];
            [_dataBase executeUpdate:@"insert into eat (cover, name) values (?, ?)", m.cover, m.name];
            
        }
        [_mainTableView reloadData];
        [_mainTableView.header endRefreshing];
    } error:^(NSError *error) {
        NSLog(@"美食列表请求错误：%@",[error localizedDescription]);
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.titleLable.text = @"美食";
    // Do any additional setup after loading the view.
    [self configureData];
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT - 113) style:(UITableViewStylePlain)];
    _mainTableView.backgroundColor = [UIColor colorWithRed:1.000 green:0.985 blue:0.971 alpha:1.000];
    _mainTableView.showsVerticalScrollIndicator = NO;
    [self.view addSubview:_mainTableView];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_mainTableView registerClass:[OPEatListCell class] forCellReuseIdentifier:@"cell"];
    _mainTableView.rowHeight = SCREEN_WIDTH*235/600;
    
    OPEatListHeadView *headView = [[OPEatListHeadView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_WIDTH*318/550+45+(SCREEN_WIDTH/2-60)*0.6)];
    _mainTableView.tableHeaderView = headView;
    UITapGestureRecognizer *mguidetap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(toguide)];
    UITapGestureRecognizer *rittipstap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(torittips)];
    [headView.mpicture addGestureRecognizer:mguidetap];
    [headView.ritpicture addGestureRecognizer:rittipstap];
    _mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self configureData];
    }];
    
    NSString *failPath = [NSSearchPathForDirectoriesInDomains(9, 1, 1).firstObject stringByAppendingPathComponent:@"OnePiece.db"];
    _dataBase = [FMDatabase databaseWithPath:failPath];
    if ([_dataBase open]) {
        NSLog(@"打开数据库成功");
        [_dataBase executeUpdate:@"create table eat (cover text, name text)"];
    }else{
        NSLog(@"打开数据库失败");
    }
    FMResultSet *resultSet = [_dataBase executeQueryWithFormat:@"select * from eat"];
    while ([resultSet next]) {
        OPEatListModel *m = [[OPEatListModel alloc]init];
        m.cover = [resultSet stringForColumn:@"cover"];
        m.name = [resultSet stringForColumn:@"name"];
        [self.dataSourceArr addObject:m];
    }
    [resultSet close];
    [_mainTableView reloadData];
    
}

- (void)toguide{
    OPEatMGuideController *mVC = [[OPEatMGuideController alloc]init];
    self.hidesBottomBarWhenPushed= YES;
    [self.navigationController pushViewController:mVC animated:YES];
    self.hidesBottomBarWhenPushed= NO;
}
- (void)torittips{
    OPEatRitListController *rVC = [[OPEatRitListController alloc]init];
    self.hidesBottomBarWhenPushed= YES;
    [self.navigationController pushViewController:rVC animated:YES];
    self.hidesBottomBarWhenPushed= NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourceArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OPEatListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    OPEatListModel *m = _dataSourceArr[indexPath.row];
    [cell setConfigureModel:m];
    return  cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    OPEatListModel *m = _dataSourceArr[indexPath.row];
    OPEatDetailController *eatDetailVC = [[OPEatDetailController alloc]init];
    eatDetailVC.eatid = m.eatid;
    self.hidesBottomBarWhenPushed= YES;
    [self.navigationController pushViewController:eatDetailVC animated:YES];
    self.hidesBottomBarWhenPushed= NO;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
